package com.example.education.controller;

import com.alibaba.fastjson.JSON;
import com.example.education.common.ResponseBuilder;
import com.example.education.exception.ParamException;
import com.example.education.model.Course;
import com.example.education.model.Evaluate;
import com.example.education.service.CourseService;
import com.example.education.service.EvaluateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import sun.net.www.http.HttpCaptureInputStream;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

@Controller
@RequestMapping("/interface/course")
public class CourseController {

    @Autowired
    CourseService courseService;
    @Autowired
    private EvaluateService evaluateService;
    @RequestMapping(value = "/insert",method = RequestMethod.POST)
    @ResponseBody
    public ResponseBuilder insertCourse(@RequestParam("file") MultipartFile file,@RequestParam("course") String courseStr) {
        FileOutputStream fos = null;
        InputStream in = null;
        try {
            Course course = JSON.parseObject(courseStr, Course.class);
            String address = String.valueOf(Math.abs(new Random().nextInt()));
            fos = new FileOutputStream("/var/img/" + address);
            byte[] bs = new byte[1024];
            in = file.getInputStream();
            while ((in.read(bs)) != -1) {
                fos.write(bs, 0, bs.length);
            }
            course.setVideoAddress(address);
            course.setPhotoAddress("/imgController/"+address);
            courseService.insertCourse(file, course);
            return ResponseBuilder.buildSuccess();
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseBuilder.buildError("失败,系统异常:" + e.getMessage());
        } finally {
            try {
                if (in != null) {

                    in.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @RequestMapping("/insertVideo")
    @ResponseBody
    public boolean insertCourseVideo(@RequestParam("file") MultipartFile file, @RequestParam("courseId") Integer courseId){
        boolean result = false;
        try {
            if(!file.getOriginalFilename().endsWith("flv")){
                return false;
            }
            result = courseService.insertCourseVideo(file,courseId);
        } catch (ParamException e) {
            e.printStackTrace();
        }
        return result;
    }

    @RequestMapping("/delete")
    @ResponseBody
    public boolean deleteCourse(Integer courseId){
        boolean result = false;
        try {
            result = courseService.deleteCourse(courseId);
        } catch (ParamException e) {
            e.printStackTrace();
        }
        return result;
    }

    @RequestMapping("/update")
    @ResponseBody
    public boolean updateCourse(Course course){
        boolean result = false;
        try {
            result = courseService.updateCourse(course);
        } catch (ParamException e) {
            e.printStackTrace();
        }
        return result;
    }

    @RequestMapping("/getById/{courseId}")
    public String  getCourseById(@PathVariable("courseId") Integer courseId, Model model){
        Course course;
        try {
            course = courseService.getCourseById(courseId);
            List<Evaluate> evaluateList = evaluateService.getEvaluateByCourseId(courseId);
            model.addAttribute("course",course);
            model.addAttribute("evaluateList",evaluateList);

        } catch (ParamException e) {
            e.printStackTrace();

        }
        return "courseInfo";
    }

    @RequestMapping("/getByIds")
    @ResponseBody
    public List<Course> getCourseByIds(List<Integer> courseIds){
        List<Course> courses = new ArrayList<>();
        try {
            courseService.getCourseByIds(courseIds);
        } catch (ParamException e) {
            e.printStackTrace();
        }
        return courses;
    }

    @RequestMapping("/getByCate")
    public ModelAndView getCourseByCateId(Integer cateId, Integer pageNum, Integer size){
        List<Course> courses = null;
        ModelAndView modelAndView = new ModelAndView("home");
        try {
            if (pageNum == null) {
                pageNum = 0;
            }
            if (size == null) {
                size = 5;
            }
            courses = courseService.getCourseByCateId(cateId, pageNum * size, size);
            modelAndView.addObject("courses",courses);
        } catch (ParamException e) {
            e.printStackTrace();
        }
        return modelAndView;
    }

    @RequestMapping("/getByWord")
    public String  getCourseByWord(String word, Integer pageNum, Integer size, Model model){
        try {
            size = 300;
            List<Course> courses = courseService.getCourseByWord(word, pageNum * size, size);
            model.addAttribute("courses",courses);
        } catch (ParamException e) {
            e.printStackTrace();
        }
        return "courseSearch";
    }

    @RequestMapping("getAll")
    @ResponseBody
    public ResponseBuilder getAllByPage(Integer page, Integer limit) {
        try {
            int allCount = courseService.getAllCount();
            List<Course> courses = courseService.selectAll(page, limit);
            return ResponseBuilder.buildPage("成功", courses, allCount);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseBuilder.buildError("失败,异常:" + e.getMessage());
        }
    }
}
